package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.data.Result;
import com.dongdongshop.pojo.admin.TbUser;
import com.dongdongshop.pojo.cart.Cart;
import com.dongdongshop.pojo.item.TbItem;
import com.dongdongshop.service.cart.CartService;
import com.dongdongshop.service.item.ItemService;
import com.dongdongshop.service.item_jpa.ItemJpaService;
import com.dongdongshop.util.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("cart")
public class CartController {
    @Reference
    private CartService cartService;
    private Logger logger = LoggerFactory.getLogger(CartController.class);
    @Reference
    private ItemService itemService;
    @Reference
    private ItemJpaService itemJpaService;
    @Value("${cart.key}")
    private String key;
    @RequestMapping("getCart")
    @ResponseBody
    public Result getCart(HttpServletRequest request,HttpServletResponse response) {
        try {
            TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
            String cartListStr = CookieUtils.getCookieValue(request, key, true);
            if (StringUtils.isBlank(cartListStr)) {
                cartListStr = "[]";
            }
            List<Cart> cartList = JSONObject.parseArray(cartListStr, Cart.class);
            if (user == null) {
                return Result.ok().setData(cartList);
            } else {
                List<Cart> cartListFromRedis = cartService.getCarListFromRedis(user.getUsername());
                if (cartList.size()>0){
                    cartListFromRedis = cartService.mergeCartListCookieAndRedis(cartList,cartListFromRedis);
                    cartService.savaCartListToRedis(user.getUsername(),cartListFromRedis);
                    CookieUtils.deleteCookie(request,response,key);
                }
                return Result.ok().setData(cartListFromRedis);
            }
            //从cookie中获取数据
        } catch (Exception e) {
            logger.error("错误", e);
            return Result.fail();
        }
    }

    @RequestMapping("setCart")
    @ResponseBody
    public Result sertCart(HttpServletResponse response,HttpServletRequest request,Long itemId,Integer num){
        List<Cart> cartList = (List<Cart>)getCart(request,response).getData();
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        try {
            List<Cart> cartList2 = cartService.addCartList(cartList,itemId,num);
            if (user==null){
                //向cookie中添加数据
                CookieUtils.setCookie(request,response,key,JSONObject.toJSONString(cartList2),true);
            }else {
                cartService.savaCartListToRedis(user.getUsername(),cartList2);
            }
        }catch (Exception e){
            logger.error("添加数据错误",e);
            return Result.fail();
        }
        return Result.ok();
    }
    //跳转成功页面
    @RequestMapping("successShow")
    public String successShow(HttpServletResponse response, HttpServletRequest request, Long itemId, Integer num, Model model){
        sertCart(response,request,itemId,num);
        model.addAttribute("itemId",itemId);
        model.addAttribute("num",num);
        return "success-cart";
    }
    //添加成功回显
    @RequestMapping("getItemById")
    @ResponseBody
    public Result getItemById(Long itemId){
        try {
            /*TbItem itemById = itemService.getItemById(itemId);*/
            TbItem itemById = itemJpaService.getItemById(itemId);
            return Result.ok().setData(itemById);
        }catch (Exception e){
            logger.error("回显失败",e);
            return Result.fail();
        }
    }
    @RequestMapping("cartShow")
    public String cartShow(){
        return "cart";
    }

}
